from django.shortcuts import render, redirect
from django.http import JsonResponse
# Create your views here.
from .models import UserInfo
from .serializer import UserInfoFormDataSerializer

import json


def login_required(func):
    '''
    语法糖：校验当前是否已经登陆
    :return:
    '''

    def inner(request, *args, **kwargs):
        if request.session.get('isLogin'):
            return func(request, *args, **kwargs)
        else:
            return redirect('/login')

    return inner


def login(request):
    '''
    登陆方法
    :param request:
    :return:
    '''
    if request.session.get('isLogin', None):
        return redirect('/index')
    return render(request, 'login.html')


# 登录ajax验证
def loginajax(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    try:
        user = UserInfo.objects.get(uname=username)
        if user.upwd == password:
            request.session['isLogin'] = True
            request.session['userId'] = user.id
            request.session['userName'] = user.uname
            return JsonResponse({'res': 1})
        else:
            return JsonResponse({'res': 0})
    except:
        return JsonResponse({'res': 2})


def logout(request):
    '''
    账号登出
    :param request:
    :return:
    '''
    if not request.session.get('isLogin', None):
        # 如果本来就未登录，也就没有登出一说
        return redirect("/index/")
    request.session.flush()
    # 或者使用下面的方法
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return redirect("/login")


@login_required
def informationUser(request):
    '''
    用户信息页面
    :param request:
    :return:
    '''

    return render(request, 'iframes/informationUser.html')


@login_required
def informationuserData(request):
    '''
      用户信息表单
      :param request:
      :return:
      '''
    allUser = UserInfo.objects.all()
    total = UserInfo.objects.count()
    userSerializer = UserInfoFormDataSerializer(allUser, many=True)
    data = userSerializer.data
    dataJson = {
        "total": total,
        "rows": data
    }
    return JsonResponse(dataJson, json_dumps_params={'ensure_ascii': False})


@login_required
def infoUserRepostrStatus(request):
    '''
    用户信息重置
    :param request:
    :return:
    '''

    try:
        useridstr = request.POST.get('userid')
        userid = int(useridstr)
        print(type(userid))
        if userid > -1:
            data = UserInfo.objects.get(id=userid)
            data.user_state = 0
            data.save()
        else:
            User = UserInfo.objects.all()
            for data in User:
                data.user_state = 0
                data.save()
        return JsonResponse({'response': 1})
    except ZeroDivisionError:
        return JsonResponse({'response': 0})
